using UnityEngine;

[ExecuteInEditMode]
public class PlatformHinge : MonoBehaviour
{
	public float width = 1f;

	public float height = 0.5f;

	public float platformLenght = 1f;

	private Vector3 initialPosition;

	private Quaternion initialRotation;

	private Rigidbody rigidbody_;

	private HingeJoint joint_;

	private void Awake()
	{
		LevelController.LevelReadyEvent += OnLevelReady;
		EventManager.WorldResetEvent += OnWorldReset;
	}

	private void OnDestroy()
	{
		LevelController.LevelReadyEvent -= OnLevelReady;
		EventManager.WorldResetEvent -= OnWorldReset;
	}

	private void OnLevelReady(Transform levelTransform)
	{
		if (base.transform.root == levelTransform)
		{
			SetDynamics();
		}
	}

	private void OnWorldReset()
	{
		if (rigidbody_ != null)
		{
			Object.DestroyImmediate(joint_);
			rigidbody_.velocity = Vector3.zero;
			rigidbody_.angularVelocity = Vector3.zero;
			rigidbody_.isKinematic = true;
			Object.DestroyImmediate(rigidbody_);
			base.transform.position = initialPosition;
			base.transform.rotation = initialRotation;
			SetDynamics();
		}
	}

	private void SetDynamics()
	{
		initialPosition = base.transform.position;
		initialRotation = base.transform.rotation;
		float num = 0.5f;
		rigidbody_ = base.gameObject.AddComponent<Rigidbody>();
		rigidbody_.mass = platformLenght * width;
		rigidbody_.maxAngularVelocity = 25f * num / platformLenght;
		rigidbody_.isKinematic = false;
		joint_ = base.gameObject.AddComponent<HingeJoint>();
		joint_.anchor = new Vector3(0f, -0.5f - height * 0.5f / platformLenght, 0f);
		joint_.axis = Vector3.right;
		joint_.enableCollision = true;
	}
}
